{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.timellm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Time-LLM"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Time-LLM is a reprogramming framework to repurpose LLMs for general time series forecasting with the backbone language models kept intact. In other words, it transforms a forecasting task into a \"language task\" that can be tackled by an off-the-shelf LLM."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**References**<br>\n",
    "- [Ming Jin, Shiyu Wang, Lintao Ma, Zhixuan Chu, James Y. Zhang, Xiaoming Shi, Pin-Yu Chen, Yuxuan Liang, Yuan-Fang Li, Shirui Pan, Qingsong Wen. \"Time-LLM: Time Series Forecasting by Reprogramming Large Language Models\"](https://arxiv.org/abs/2310.01728)<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Figure 1. Time-LLM Architecture.](imgs_models/timellm.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "import math\n",
    "from typing import Optional\n",
    "\n",
    "import neuralforecast.losses.pytorch as losses\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "from neuralforecast.common._base_model import BaseModel\n",
    "from neuralforecast.common._modules import RevIN\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "\n",
    "try:\n",
    "    from transformers import AutoModel, AutoTokenizer, AutoConfig\n",
    "    IS_TRANSFORMERS_INSTALLED = True\n",
    "except ImportError:\n",
    "    IS_TRANSFORMERS_INSTALLED = False\n",
    "\n",
    "import warnings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.common._model_checks import check_model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Auxiliary Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "class ReplicationPad1d(nn.Module):\n",
    "    \"\"\"\n",
    "    ReplicationPad1d\n",
    "    \"\"\"       \n",
    "    def __init__(self, padding):\n",
    "        super(ReplicationPad1d, self).__init__()\n",
    "        self.padding = padding\n",
    "\n",
    "    def forward(self, input):\n",
    "        replicate_padding = input[:, :, -1].unsqueeze(-1).repeat(1, 1, self.padding[-1])\n",
    "        output = torch.cat([input, replicate_padding], dim=-1)\n",
    "        return output\n",
    "    \n",
    "class TokenEmbedding(nn.Module):\n",
    "    \"\"\"\n",
    "    TokenEmbedding\n",
    "    \"\"\"       \n",
    "    def __init__(self, c_in, d_model):\n",
    "        super(TokenEmbedding, self).__init__()\n",
    "        padding = 1 if torch.__version__ >= '1.5.0' else 2\n",
    "        self.tokenConv = nn.Conv1d(in_channels=c_in, out_channels=d_model,\n",
    "                                   kernel_size=3, padding=padding, padding_mode='circular', bias=False)\n",
    "        for m in self.modules():\n",
    "            if isinstance(m, nn.Conv1d):\n",
    "                nn.init.kaiming_normal_(\n",
    "                    m.weight, mode='fan_in', nonlinearity='leaky_relu')\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.tokenConv(x.permute(0, 2, 1)).transpose(1, 2)\n",
    "        return x\n",
    "    \n",
    "class PatchEmbedding(nn.Module):\n",
    "    \"\"\"\n",
    "    PatchEmbedding\n",
    "    \"\"\"      \n",
    "    def __init__(self, d_model, patch_len, stride, dropout):\n",
    "        super(PatchEmbedding, self).__init__()\n",
    "        # Patching\n",
    "        self.patch_len = patch_len\n",
    "        self.stride = stride\n",
    "        self.padding_patch_layer = ReplicationPad1d((0, stride))\n",
    "\n",
    "        # Backbone, Input encoding: projection of feature vectors onto a d-dim vector space\n",
    "        self.value_embedding = TokenEmbedding(patch_len, d_model)\n",
    "\n",
    "        # Positional embedding\n",
    "        # self.position_embedding = PositionalEmbedding(d_model)\n",
    "\n",
    "        # Residual dropout\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "\n",
    "    def forward(self, x):\n",
    "        # do patching\n",
    "        n_vars = x.shape[1]\n",
    "        x = self.padding_patch_layer(x)\n",
    "        x = x.unfold(dimension=-1, size=self.patch_len, step=self.stride)\n",
    "        x = torch.reshape(x, (x.shape[0] * x.shape[1], x.shape[2], x.shape[3]))\n",
    "        # Input encoding\n",
    "        x = self.value_embedding(x)\n",
    "        return self.dropout(x), n_vars\n",
    "    \n",
    "class FlattenHead(nn.Module):\n",
    "    \"\"\"\n",
    "    FlattenHead\n",
    "    \"\"\"       \n",
    "    def __init__(self, n_vars, nf, target_window, head_dropout=0):\n",
    "        super().__init__()\n",
    "        self.n_vars = n_vars\n",
    "        self.flatten = nn.Flatten(start_dim=-2)\n",
    "        self.linear = nn.Linear(nf, target_window)\n",
    "        self.dropout = nn.Dropout(head_dropout)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.flatten(x)\n",
    "        x = self.linear(x)\n",
    "        x = self.dropout(x)\n",
    "        return x\n",
    "    \n",
    "class ReprogrammingLayer(nn.Module):\n",
    "    \"\"\"\n",
    "    ReprogrammingLayer\n",
    "    \"\"\"       \n",
    "    def __init__(self, d_model, n_heads, d_keys=None, d_llm=None, attention_dropout=0.1):\n",
    "        super(ReprogrammingLayer, self).__init__()\n",
    "\n",
    "        d_keys = d_keys or (d_model // n_heads)\n",
    "\n",
    "        self.query_projection = nn.Linear(d_model, d_keys * n_heads)\n",
    "        self.key_projection = nn.Linear(d_llm, d_keys * n_heads)\n",
    "        self.value_projection = nn.Linear(d_llm, d_keys * n_heads)\n",
    "        self.out_projection = nn.Linear(d_keys * n_heads, d_llm)\n",
    "        self.n_heads = n_heads\n",
    "        self.dropout = nn.Dropout(attention_dropout)\n",
    "\n",
    "    def forward(self, target_embedding, source_embedding, value_embedding):\n",
    "        B, L, _ = target_embedding.shape\n",
    "        S, _ = source_embedding.shape\n",
    "        H = self.n_heads\n",
    "\n",
    "        target_embedding = self.query_projection(target_embedding).view(B, L, H, -1)\n",
    "        source_embedding = self.key_projection(source_embedding).view(S, H, -1)\n",
    "        value_embedding = self.value_projection(value_embedding).view(S, H, -1)\n",
    "\n",
    "        out = self.reprogramming(target_embedding, source_embedding, value_embedding)\n",
    "\n",
    "        out = out.reshape(B, L, -1)\n",
    "\n",
    "        return self.out_projection(out)\n",
    "\n",
    "    def reprogramming(self, target_embedding, source_embedding, value_embedding):\n",
    "        B, L, H, E = target_embedding.shape\n",
    "\n",
    "        scale = 1. / math.sqrt(E)\n",
    "\n",
    "        scores = torch.einsum(\"blhe,she->bhls\", target_embedding, source_embedding)\n",
    "\n",
    "        A = self.dropout(torch.softmax(scale * scores, dim=-1))\n",
    "        reprogramming_embedding = torch.einsum(\"bhls,she->blhe\", A, value_embedding)\n",
    "\n",
    "        return reprogramming_embedding\n",
    "    \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "class TimeLLM(BaseModel):\n",
    "\n",
    "    \"\"\" TimeLLM\n",
    "\n",
    "    Time-LLM is a reprogramming framework to repurpose an off-the-shelf LLM for time series forecasting.\n",
    "\n",
    "    It trains a reprogramming layer that translates the observed series into a language task. This is fed to the LLM and an output\n",
    "    projection layer translates the output back to numerical predictions.\n",
    "\n",
    "    **Parameters:**<br>\n",
    "    `h`: int, Forecast horizon. <br>\n",
    "    `input_size`: int, autorregresive inputs size, y=[1,2,3,4] input_size=2 -> y_[t-2:t]=[1,2].<br>\n",
    "    `patch_len`: int=16, length of patch.<br>\n",
    "    `stride`: int=8, stride of patch.<br>\n",
    "    `d_ff`: int=128, dimension of fcn.<br>\n",
    "    `top_k`: int=5, top tokens to consider.<br>\n",
    "    `d_llm`: int=768, hidden dimension of LLM.<br> # LLama7b:4096; GPT2-small:768; BERT-base:768\n",
    "    `d_model`: int=32, dimension of model.<br>\n",
    "    `n_heads`: int=8, number of heads in attention layer.<br>\n",
    "    `enc_in`: int=7, encoder input size.<br>\n",
    "    `dec_in`: int=7, decoder input size.<br>\n",
    "    `llm` = None, Path to pretrained LLM model to use. If not specified, it will use GPT-2 from https://huggingface.co/openai-community/gpt2\"<br>\n",
    "    `llm_config` = Deprecated, configuration of LLM. If not specified, it will use the configuration of GPT-2 from https://huggingface.co/openai-community/gpt2\"<br>\n",
    "    `llm_tokenizer` = Deprecated, tokenizer of LLM. If not specified, it will use the GPT-2 tokenizer from https://huggingface.co/openai-community/gpt2\"<br>\n",
    "    `llm_num_hidden_layers` = 32, hidden layers in LLM\n",
    "    `llm_output_attention`: bool = True, whether to output attention in encoder.<br>\n",
    "    `llm_output_hidden_states`: bool = True, whether to output hidden states.<br>\n",
    "    `prompt_prefix`: str=None, prompt to inform the LLM about the dataset.<br>\n",
    "    `dropout`: float=0.1, dropout rate.<br>\n",
    "    `stat_exog_list`: str list, static exogenous columns.<br>\n",
    "    `hist_exog_list`: str list, historic exogenous columns.<br>\n",
    "    `futr_exog_list`: str list, future exogenous columns.<br>\n",
    "    `loss`: PyTorch module, instantiated train loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `valid_loss`: PyTorch module=`loss`, instantiated valid loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `learning_rate`: float=1e-3, Learning rate between (0, 1).<br>\n",
    "    `max_steps`: int=1000, maximum number of training steps.<br>\n",
    "    `val_check_steps`: int=100, Number of training steps between every validation loss check.<br>\n",
    "    `batch_size`: int=32, number of different series in each batch.<br>\n",
    "    `valid_batch_size`: int=None, number of different series in each validation and test batch, if None uses batch_size.<br>\n",
    "    `windows_batch_size`: int=1024, number of windows to sample in each training batch, default uses all.<br>\n",
    "    `inference_windows_batch_size`: int=1024, number of windows to sample in each inference batch.<br>\n",
    "    `start_padding_enabled`: bool=False, if True, the model will pad the time series with zeros at the beginning, by input size.<br>\n",
    "    `step_size`: int=1, step size between each window of temporal data.<br>\n",
    "    `num_lr_decays`: int=-1, Number of learning rate decays, evenly distributed across max_steps.<br>\n",
    "    `early_stop_patience_steps`: int=-1, Number of validation iterations before early stopping.<br>\n",
    "    `scaler_type`: str='identity', type of scaler for temporal inputs normalization see [temporal scalers](https://nixtla.github.io/neuralforecast/common.scalers.html).<br>\n",
    "    `random_seed`: int, random_seed for pytorch initializer and numpy generators.<br>\n",
    "    `drop_last_loader`: bool=False, if True `TimeSeriesDataLoader` drops last non-full batch.<br>\n",
    "    `alias`: str, optional,  Custom name of the model.<br>\n",
    "    `optimizer`: Subclass of 'torch.optim.Optimizer', optional, user specified optimizer instead of the default choice (Adam).<br>\n",
    "    `optimizer_kwargs`: dict, optional, list of parameters used by the user specified `optimizer`.<br>    \n",
    "    `lr_scheduler`: Subclass of 'torch.optim.lr_scheduler.LRScheduler', optional, user specified lr_scheduler instead of the default choice (StepLR).<br>\n",
    "    `lr_scheduler_kwargs`: dict, optional, list of parameters used by the user specified `lr_scheduler`.<br>\n",
    "    `dataloader_kwargs`: dict, optional, list of parameters passed into the PyTorch Lightning dataloader by the `TimeSeriesDataLoader`. <br>\n",
    "    `**trainer_kwargs`: int,  keyword trainer arguments inherited from [PyTorch Lighning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).<br>    \n",
    "\n",
    "    **References:**<br>\n",
    "    -[Ming Jin, Shiyu Wang, Lintao Ma, Zhixuan Chu, James Y. Zhang, Xiaoming Shi, Pin-Yu Chen, Yuxuan Liang, Yuan-Fang Li, Shirui Pan, Qingsong Wen. \"Time-LLM: Time Series Forecasting by Reprogramming Large Language Models\"](https://arxiv.org/abs/2310.01728)\n",
    "    \n",
    "    \"\"\"\n",
    "\n",
    "    EXOGENOUS_FUTR = False\n",
    "    EXOGENOUS_HIST = False\n",
    "    EXOGENOUS_STAT = False\n",
    "    MULTIVARIATE = False    # If the model produces multivariate forecasts (True) or univariate (False)\n",
    "    RECURRENT = False       # If the model produces forecasts recursively (True) or direct (False)\n",
    "\n",
    "    def __init__(self,\n",
    "                 h,\n",
    "                 input_size,\n",
    "                 patch_len: int = 16,\n",
    "                 stride: int = 8,\n",
    "                 d_ff: int = 128,\n",
    "                 top_k: int = 5,\n",
    "                 d_llm: int = 768,\n",
    "                 d_model: int = 32,\n",
    "                 n_heads: int = 8,\n",
    "                 enc_in: int = 7,\n",
    "                 dec_in: int  = 7,\n",
    "                 llm = None,\n",
    "                 llm_config = None,\n",
    "                 llm_tokenizer = None,\n",
    "                 llm_num_hidden_layers = 32,\n",
    "                 llm_output_attention: bool = True,\n",
    "                 llm_output_hidden_states: bool = True,\n",
    "                 prompt_prefix: Optional[str] = None,\n",
    "                 dropout: float = 0.1,\n",
    "                 stat_exog_list = None,\n",
    "                 hist_exog_list = None,\n",
    "                 futr_exog_list = None,\n",
    "                 loss = MAE(),\n",
    "                 valid_loss = None,\n",
    "                 learning_rate: float = 1e-4,\n",
    "                 max_steps: int = 5,\n",
    "                 val_check_steps: int = 100,\n",
    "                 batch_size: int = 32,\n",
    "                 valid_batch_size: Optional[int] = None,\n",
    "                 windows_batch_size: int = 1024,\n",
    "                 inference_windows_batch_size: int = 1024,\n",
    "                 start_padding_enabled: bool = False,\n",
    "                 step_size: int = 1,\n",
    "                 num_lr_decays: int = 0,\n",
    "                 early_stop_patience_steps: int = -1,\n",
    "                 scaler_type: str = 'identity',\n",
    "                 random_seed: int = 1,\n",
    "                 drop_last_loader: bool = False,\n",
    "                 alias: Optional[str] = None,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 lr_scheduler = None,\n",
    "                 lr_scheduler_kwargs = None,\n",
    "                 dataloader_kwargs = None,\n",
    "                 **trainer_kwargs):\n",
    "        super(TimeLLM, self).__init__(h=h,\n",
    "                                      input_size=input_size,\n",
    "                                      hist_exog_list=hist_exog_list,\n",
    "                                      stat_exog_list=stat_exog_list,\n",
    "                                      futr_exog_list = futr_exog_list,\n",
    "                                      loss=loss,\n",
    "                                      valid_loss=valid_loss,\n",
    "                                      max_steps=max_steps,\n",
    "                                      learning_rate=learning_rate,\n",
    "                                      num_lr_decays=num_lr_decays,\n",
    "                                      early_stop_patience_steps=early_stop_patience_steps,\n",
    "                                      val_check_steps=val_check_steps,\n",
    "                                      batch_size=batch_size,\n",
    "                                      valid_batch_size=valid_batch_size,\n",
    "                                      windows_batch_size=windows_batch_size,\n",
    "                                      inference_windows_batch_size=inference_windows_batch_size,\n",
    "                                      start_padding_enabled=start_padding_enabled,\n",
    "                                      step_size=step_size,\n",
    "                                      scaler_type=scaler_type,\n",
    "                                      drop_last_loader=drop_last_loader,\n",
    "                                      alias=alias,\n",
    "                                      random_seed=random_seed,\n",
    "                                      optimizer=optimizer,\n",
    "                                      optimizer_kwargs=optimizer_kwargs,\n",
    "                                      lr_scheduler=lr_scheduler,\n",
    "                                      lr_scheduler_kwargs=lr_scheduler_kwargs,\n",
    "                                      dataloader_kwargs=dataloader_kwargs,\n",
    "                                      **trainer_kwargs)\n",
    "        if loss.outputsize_multiplier > 1:\n",
    "            raise Exception('TimeLLM only supports point loss functions (MAE, MSE, etc) as loss function.')               \n",
    "    \n",
    "        if valid_loss is not None and not isinstance(valid_loss, losses.BasePointLoss):\n",
    "            raise Exception('TimeLLM only supports point loss functions (MAE, MSE, etc) as valid loss function.') \n",
    "\n",
    "\n",
    "        # Architecture\n",
    "        self.patch_len = patch_len\n",
    "        self.stride = stride\n",
    "        self.d_ff = d_ff\n",
    "        self.top_k = top_k\n",
    "        self.d_llm = d_llm\n",
    "        self.d_model = d_model\n",
    "        self.dropout = dropout\n",
    "        self.n_heads = n_heads\n",
    "        self.enc_in = enc_in\n",
    "        self.dec_in = dec_in\n",
    "\n",
    "        DEFAULT_MODEL = \"openai-community/gpt2\"\n",
    "\n",
    "        if llm is None:\n",
    "            if not IS_TRANSFORMERS_INSTALLED:\n",
    "                raise ImportError(\n",
    "                    \"Please install `transformers` to use the default LLM.\"\n",
    "                )\n",
    "                  \n",
    "            print(f\"Using {DEFAULT_MODEL} as default.\")\n",
    "            model_name = DEFAULT_MODEL\n",
    "        else:\n",
    "            model_name = llm\n",
    "\n",
    "        if llm_config is not None or llm_tokenizer is not None:\n",
    "            warnings.warn(\"'llm_config' and 'llm_tokenizer' parameters are deprecated and will be ignored. \"\n",
    "                        \"The config and tokenizer will be automatically loaded from the specified model.\", \n",
    "                        DeprecationWarning)\n",
    "\n",
    "        try:\n",
    "            self.llm_config = AutoConfig.from_pretrained(model_name)\n",
    "            self.llm = AutoModel.from_pretrained(model_name, config=self.llm_config)\n",
    "            self.llm_tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
    "            print(f\"Successfully loaded model: {model_name}\")\n",
    "        except EnvironmentError:\n",
    "            print(f\"Failed to load {model_name}. Loading the default model ({DEFAULT_MODEL})...\")\n",
    "            self.llm_config = AutoConfig.from_pretrained(DEFAULT_MODEL)\n",
    "            self.llm = AutoModel.from_pretrained(DEFAULT_MODEL, config=self.llm_config)\n",
    "            self.llm_tokenizer = AutoTokenizer.from_pretrained(DEFAULT_MODEL)\n",
    "\n",
    "        self.llm_num_hidden_layers = llm_num_hidden_layers\n",
    "        self.llm_output_attention = llm_output_attention\n",
    "        self.llm_output_hidden_states = llm_output_hidden_states\n",
    "        self.prompt_prefix = prompt_prefix\n",
    "\n",
    "        if self.llm_tokenizer.eos_token:\n",
    "            self.llm_tokenizer.pad_token = self.llm_tokenizer.eos_token\n",
    "        else:\n",
    "            pad_token = '[PAD]'\n",
    "            self.llm_tokenizer.add_special_tokens({'pad_token': pad_token})\n",
    "            self.llm_tokenizer.pad_token = pad_token\n",
    "\n",
    "        for param in self.llm.parameters():\n",
    "            param.requires_grad = False\n",
    "\n",
    "        self.patch_embedding = PatchEmbedding(\n",
    "            self.d_model, self.patch_len, self.stride, self.dropout)\n",
    "        \n",
    "        self.word_embeddings = self.llm.get_input_embeddings().weight\n",
    "        self.vocab_size = self.word_embeddings.shape[0]\n",
    "        self.num_tokens = 1024\n",
    "        self.mapping_layer = nn.Linear(self.vocab_size, self.num_tokens)\n",
    "\n",
    "        self.reprogramming_layer = ReprogrammingLayer(self.d_model, self.n_heads, self.d_ff, self.d_llm)\n",
    "\n",
    "        self.patch_nums = int((input_size - self.patch_len) / self.stride + 2)\n",
    "        self.head_nf = self.d_ff * self.patch_nums\n",
    "\n",
    "        self.output_projection = FlattenHead(self.enc_in, self.head_nf, self.h, head_dropout=self.dropout)\n",
    "\n",
    "        self.normalize_layers = RevIN(self.enc_in, affine=False)\n",
    "\n",
    "    def forecast(self, x_enc):\n",
    "\n",
    "        x_enc = self.normalize_layers(x_enc, 'norm')\n",
    "\n",
    "        B, T, N = x_enc.size()\n",
    "        x_enc = x_enc.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)\n",
    "\n",
    "        min_values = torch.min(x_enc, dim=1)[0]\n",
    "        max_values = torch.max(x_enc, dim=1)[0]\n",
    "        medians = torch.median(x_enc, dim=1).values\n",
    "        lags = self.calcute_lags(x_enc)\n",
    "        trends = x_enc.diff(dim=1).sum(dim=1)\n",
    "\n",
    "        prompt = []\n",
    "        for b in range(x_enc.shape[0]):\n",
    "            min_values_str = str(min_values[b].tolist()[0])\n",
    "            max_values_str = str(max_values[b].tolist()[0])\n",
    "            median_values_str = str(medians[b].tolist()[0])\n",
    "            lags_values_str = str(lags[b].tolist())\n",
    "            prompt_ = (\n",
    "                f\"<|start_prompt|>{self.prompt_prefix}\"\n",
    "                f\"Task description: forecast the next {str(self.h)} steps given the previous {str(self.input_size)} steps information; \"\n",
    "                \"Input statistics: \"\n",
    "                f\"min value {min_values_str}, \"\n",
    "                f\"max value {max_values_str}, \"\n",
    "                f\"median value {median_values_str}, \"\n",
    "                f\"the trend of input is {'upward' if trends[b] > 0 else 'downward'}, \"\n",
    "                f\"top 5 lags are : {lags_values_str}<|<end_prompt>|>\"\n",
    "            )\n",
    "\n",
    "            prompt.append(prompt_)\n",
    "\n",
    "        x_enc = x_enc.reshape(B, N, T).permute(0, 2, 1).contiguous()\n",
    "\n",
    "        prompt = self.llm_tokenizer(prompt, return_tensors=\"pt\", padding=True, truncation=True, max_length=2048).input_ids\n",
    "        prompt_embeddings = self.llm.get_input_embeddings()(prompt.to(x_enc.device))  # (batch, prompt_token, dim)\n",
    "\n",
    "        source_embeddings = self.mapping_layer(self.word_embeddings.permute(1, 0)).permute(1, 0)\n",
    "\n",
    "        x_enc = x_enc.permute(0, 2, 1).contiguous()\n",
    "        enc_out, n_vars = self.patch_embedding(x_enc.to(torch.float32))\n",
    "        enc_out = self.reprogramming_layer(enc_out, source_embeddings, source_embeddings)\n",
    "        llm_enc_out = torch.cat([prompt_embeddings, enc_out], dim=1)\n",
    "        dec_out = self.llm(inputs_embeds=llm_enc_out).last_hidden_state\n",
    "        dec_out = dec_out[:, :, :self.d_ff]\n",
    "\n",
    "        dec_out = torch.reshape(\n",
    "            dec_out, (-1, n_vars, dec_out.shape[-2], dec_out.shape[-1]))\n",
    "        dec_out = dec_out.permute(0, 1, 3, 2).contiguous()\n",
    "\n",
    "        dec_out = self.output_projection(dec_out[:, :, :, -self.patch_nums:])\n",
    "        dec_out = dec_out.permute(0, 2, 1).contiguous()\n",
    "\n",
    "        dec_out = self.normalize_layers(dec_out, 'denorm')\n",
    "\n",
    "        return dec_out\n",
    "        \n",
    "    def calcute_lags(self, x_enc):\n",
    "        q_fft = torch.fft.rfft(x_enc.permute(0, 2, 1).contiguous(), dim=-1)\n",
    "        k_fft = torch.fft.rfft(x_enc.permute(0, 2, 1).contiguous(), dim=-1)\n",
    "        res = q_fft * torch.conj(k_fft)\n",
    "        corr = torch.fft.irfft(res, dim=-1)\n",
    "        mean_value = torch.mean(corr, dim=1)\n",
    "        _, lags = torch.topk(mean_value, self.top_k, dim=-1)\n",
    "        return lags\n",
    "    \n",
    "    def forward(self, windows_batch):\n",
    "        x = windows_batch['insample_y']\n",
    "\n",
    "        y_pred = self.forecast(x)\n",
    "        y_pred = y_pred[:, -self.h:, :]\n",
    "        \n",
    "        return y_pred\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TimeLLM)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TimeLLM.fit, name='TimeLLM.fit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TimeLLM.predict, name='TimeLLM.predict')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Usage example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import TimeLLM\n",
    "from neuralforecast.utils import AirPassengersPanel\n",
    "\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "prompt_prefix = \"The dataset contains data on monthly air passengers. There is a yearly seasonality\"\n",
    "\n",
    "timellm = TimeLLM(h=12,\n",
    "                 input_size=36,\n",
    "                 llm='openai-community/gpt2',\n",
    "                 prompt_prefix=prompt_prefix,\n",
    "                 batch_size=16,\n",
    "                 valid_batch_size=16,\n",
    "                 windows_batch_size=16)\n",
    "\n",
    "nf = NeuralForecast(\n",
    "    models=[timellm],\n",
    "    freq='ME'\n",
    ")\n",
    "\n",
    "nf.fit(df=Y_train_df, val_size=12)\n",
    "forecasts = nf.predict(futr_df=Y_test_df)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
